package com.job.updateinfojob.job;//package com.digitalgd.ds.datacenter.datamap.search.server.updateinfobyoshi.job;



import com.job.updateinfojob.entity.DisksInfoEntity;
import com.job.updateinfojob.entity.NetworkInfoEntity;
import com.job.updateinfojob.entity.OsInfoEntity;
import com.job.updateinfojob.entity.OsRunTimeInfoEntity;
import com.job.updateinfojob.model.DisksInfo;
import com.job.updateinfojob.model.NetworkInfo;
import com.job.updateinfojob.model.OSInfo;
import com.job.updateinfojob.model.OSRuntimeInfo;
import com.job.updateinfojob.service.IDisksInfoService;
import com.job.updateinfojob.service.INetworkInfoService;
import com.job.updateinfojob.service.IOSInfoService;
import com.job.updateinfojob.service.IOSRuntimeInfoService;
import com.job.updateinfojob.util.SnowUtil;
import com.job.updateinfojob.util.SystemInfoUtil;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Property;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 定时任务
 * @author xqf
 */
@Data
@Slf4j
@Component
@EnableScheduling
public class updateInfoJob implements SchedulingConfigurer {

    @Value("${job.interval}")
    private String cron;

    @Resource
    private INetworkInfoService iNetworkInfoService;
    @Resource
    private IOSInfoService iosInfoService;
    @Resource
    private IDisksInfoService iDisksInfoService;
    @Resource
    private IOSRuntimeInfoService iosRuntimeInfoService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(() ->
                log.info("Current time： {}", LocalDateTime.now()), new Trigger() {
            @SneakyThrows
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {

                log.info("-----------开始读取系统信息----------------");
                //1.读取系统信息
                OSInfo osInfo = SystemInfoUtil.getSystemInfo();
                //2.读取网卡信息
                List<NetworkInfo> networkInfoList = SystemInfoUtil.getNetworkInfo();
                //3.读取系统运行时信息
                OSRuntimeInfo osRuntimeInfo = SystemInfoUtil.getOSRuntimeInfo();
                //4.读取磁盘信息
                List<DisksInfo> disksInfoList = SystemInfoUtil.getDisksList();
                log.info("-----------读取系统信息完毕----------------");
                OsInfoEntity osInfoEntity = new OsInfoEntity();
                osInfoEntity.setId(SnowUtil.getSnowflakeNextId());
                osInfoEntity.setOs(osInfo.getOs());
                osInfoEntity.setOsArch(osInfo.getOsArch());
                osInfoEntity.setHostName(osInfo.getHostName());

                List<NetworkInfoEntity> networkInfoEntityList = new LinkedList<>();
                for (NetworkInfo networkInfo : networkInfoList) {
                    NetworkInfoEntity networkInfoEntity = new NetworkInfoEntity();
                    networkInfoEntity.setIpv4Address(networkInfo.getIpv4Address());
                    networkInfoEntity.setIpv6Address(networkInfo.getIpv6Address());
                    networkInfoEntity.setMacAddress(networkInfo.getMacAddress());
                    networkInfoEntity.setNetworkName(networkInfo.getNetworkName());
                    networkInfoEntity.setSend(networkInfo.getSend());
                    networkInfoEntity.setAccept(networkInfo.getAccept());
                    networkInfoEntity.setTimeStamp(String.valueOf(networkInfo.getTimeStamp()));
                    networkInfoEntity.setOsId(osInfoEntity.getId());
                    networkInfoEntityList.add(networkInfoEntity);
                }



                OsRunTimeInfoEntity osRuntimeInfoEntity=new OsRunTimeInfoEntity();
                osRuntimeInfoEntity.setTimestamp(osRuntimeInfo.getTimestamp());
                osRuntimeInfoEntity.setCpuUsage(osRuntimeInfo.getCpuUsage());
                osRuntimeInfoEntity.setCpuMaxfreq(osRuntimeInfo.getCpuMaxFreq());
                osRuntimeInfoEntity.setCpuCurrentfreq(osRuntimeInfo.getCpuCurrentFreq());
                osRuntimeInfoEntity.setTotalMemory(osRuntimeInfo.getTotalMemory());
                osRuntimeInfoEntity.setUseMemory(osRuntimeInfo.getUsedMemory());
                osRuntimeInfoEntity.setSwapTotalMemory(osRuntimeInfo.getSwapTotalMemory());
                osRuntimeInfoEntity.setSwapUsedMemory(osRuntimeInfo.getSwapUsedMemory());
                osRuntimeInfoEntity.setDiskReadRate(osRuntimeInfo.getDiskReadRate());
                osRuntimeInfoEntity.setDiskWriteRate(osRuntimeInfo.getDiskWriteRate());
                osRuntimeInfoEntity.setOsId(osInfoEntity.getId());



                List<DisksInfoEntity> disksInfoEntityList = new LinkedList<>();
                for (DisksInfo disksInfo : disksInfoList) {
                    DisksInfoEntity disksInfoEntity = new DisksInfoEntity();
                    disksInfoEntity.setDirName(disksInfo.getDirName());
                    disksInfoEntity.setSysTypeName(disksInfo.getSysTypeName());
                    disksInfoEntity.setTypeName(disksInfo.getTypeName());
                    disksInfoEntity.setTotal(disksInfo.getTotal());
                    disksInfoEntity.setFree(disksInfo.getFree());
                    disksInfoEntity.setUsed(disksInfo.getUsed());
                    disksInfoEntity.setUsage1(disksInfo.getUsage());
                    disksInfoEntity.setOsId(osInfoEntity.getId());
                    disksInfoEntityList.add(disksInfoEntity);
                }

                System.out.println(disksInfoList.size()+":"+disksInfoEntityList.size());

                //2.insert/update到mysql中
                try {
                    transactionTemplate.execute(status -> {
                        try {
                            log.info("--------开始插入系统信息-------------");
                            // 插入系统信息
                            iosInfoService.insert(osInfoEntity);
                            // 插入网卡信息
                            iNetworkInfoService.insert(networkInfoEntityList);
                            // 插入系统运行时信息
                            iosRuntimeInfoService.insert(osRuntimeInfoEntity);
                            // 插入磁盘信息
                            iDisksInfoService.insert(disksInfoEntityList);
                            log.info("--------插入系统信息完毕-------------");
                            return 1;
                        } catch (DuplicateKeyException e) {
                            log.info("插入系统信息error...");
                        }
                        return 1;
                    });
                } finally {
                }


                CronTrigger cronTrigger = new CronTrigger(cron);
                Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
                return nextExecutionTime;
            }
        });
    }
}

